﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Pur
{
    public partial class frmMaintainPurchaseApplication : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public PurApplicationEntity SelectedPurApplication { get; set; }
        private List<PurApplicationItemEntity> DeleteList = new List<PurApplicationItemEntity>();

        private List<SalesProdPlanApplicationItemEntity> mListApplicationItems;
        #endregion

        #region Constructor
        public frmMaintainPurchaseApplication()
        {
            InitializeComponent();
            if (SelectedPurApplication == null)
            {
                SelectedPurApplication = new PurApplicationEntity();
                SelectedPurApplication.ApplicationId = Guid.NewGuid().ToString();
            }
        }
        #endregion

        #region Functions
        private void SetFieldsByProdPlanOrder(List<ProdPlanOrderEntity> list)
        {
            if (list == null)
            {
                return;
            }
            if (SelectedPurApplication == null)
            {
                SelectedPurApplication = new PurApplicationEntity();
                SelectedPurApplication.ApplicationId = Guid.NewGuid().ToString();
            }
            SelectedPurApplication.IsProductPurchase = 0;

            SetFields();

            DataTable dt = gvMain.DataSource as DataTable;
            foreach(DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Added)
                {
                    PurApplicationItemEntity entity = new PurApplicationItemEntity(dr);
                    DeleteList.Add(entity);
                }
                dt.Rows.Remove(dr);
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbIsProductPurchase, typeof(PurchaseCategory), typeof(int), false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPurchaseType, "PURTYPE", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            if (SelectedPurApplication == null)
            {
                gvMain.DataSource = null;
                return;
            }
            DataSet ds = PurApplicationItemBs.GetDataSetByApplicationID(SelectedPurApplication.ApplicationId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<PurApplicationItemEntity>();
            ResetTotalAmount();
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedPurApplication == null)
            {
                return;
            }
            txtApplicationCode.Text = SelectedPurApplication.ApplicationCode;
            if (string.IsNullOrEmpty(txtApplicationCode.Text))
            {
                txtApplicationCode.Text = "自动生成";
            }
            if (SelectedPurApplication.ApplicationDate.ToString("yyyy-MM-dd") != "1900-01-01"
                && SelectedPurApplication.ApplicationDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpApplicationDate.EditValue = SelectedPurApplication.ApplicationDate;
            }
            if (SelectedPurApplication.DeliveryRequiredDate.ToString("yyyy-MM-dd") != "1900-01-01"
                && SelectedPurApplication.DeliveryRequiredDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpDeliveryRequiredDate.EditValue = SelectedPurApplication.DeliveryRequiredDate;
            }
            if (SelectedPurApplication.DeliveryPlanDate.ToString("yyyy-MM-dd") != "1900-01-01"
                && SelectedPurApplication.DeliveryPlanDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpDeliveryPlanDate.EditValue = SelectedPurApplication.DeliveryPlanDate;
            }
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtApplicationPerson.Tag = person;
                    txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedPurApplication.ApplicationPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedPurApplication.ApplicationPerson);
                    if (person != null)
                    {
                        txtApplicationPerson.Tag = person;
                        txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            cmbIsProductPurchase.SetSelectedValue(SelectedPurApplication.IsProductPurchase);
            cmbPurchaseType.SetSelectedValue(SelectedPurApplication.PurchaseType);
            cmbStatus.SetSelectedValue(SelectedPurApplication.Status);
            txtRemark.Text = SelectedPurApplication.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedPurApplication.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedPurApplication.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedPurApplication.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedPurApplication.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedPurApplication.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedPurApplication.ApprovedBy);
        }

        private void SetEntity()
        {
            if (dtpApplicationDate.EditValue!=null)
            {
                SelectedPurApplication.ApplicationDate = (DateTime)dtpApplicationDate.EditValue;
            }
            if (dtpDeliveryRequiredDate.EditValue!=null)
            {
                SelectedPurApplication.DeliveryRequiredDate = (DateTime)dtpDeliveryRequiredDate.EditValue;
            }
            if (dtpDeliveryPlanDate.EditValue!=null)
            {
                SelectedPurApplication.DeliveryPlanDate = (DateTime)dtpDeliveryPlanDate.EditValue;
            }
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedPurApplication.ApplicationPerson = ((MstPersonEntity)txtApplicationPerson.Tag).PersonId;
            }
            if (cmbIsProductPurchase.SelectedValue != null && cmbIsProductPurchase.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurApplication.IsProductPurchase = CommonFunctions.ToInt32(cmbIsProductPurchase.SelectedValue);
            }
            if (cmbPurchaseType.SelectedValue != null && cmbPurchaseType.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurApplication.PurchaseType = cmbPurchaseType.SelectedValue.ToString().Trim();
            }
            SelectedPurApplication.Status = NormalStatus.STATUS02.ToString();
            SelectedPurApplication.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedPurApplication.CreatedDate = DateTime.Now;
                SelectedPurApplication.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedPurApplication.LastModifiedDate = DateTime.Now;
                SelectedPurApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private void ResetTotalAmount()
        {
            decimal totalAmount = 0;
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"].ToString() == "")
                {
                    continue;
                }
                totalAmount += Convert.ToDecimal(dr["TOTAL_AMOUNT"].ToString());
            }
            txtTotalAmount.Text = totalAmount.ToString("0.00");
        }

        private bool CheckData()
        {
            if (dtpApplicationDate.EditValue == null)
            {
                MessageBox.Show("申请日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbIsProductPurchase.SelectedValue == null || cmbIsProductPurchase.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPurchaseType.SelectedValue == null || cmbPurchaseType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtApplicationPerson.Text))
            {
                MessageBox.Show("申请人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (gvMain.DataSource == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("采购申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurApplicationBs.SaveApplication(true, SelectedPurApplication, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurApplicationBs.SaveApplication(false, SelectedPurApplication, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedPurApplication.ApprovedDate = DateTime.Now;
                    SelectedPurApplication.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = PurApplicationBs.ApprovePurchaseApplication(SelectedPurApplication);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            if (this.ThisActionType == ActionType.View)
            {
                gridView1.OptionsBehavior.Editable = false;
            }            
            BindComboBox();
            SetFields();
            base.OnShown(e);
        }

        private DataRow drApplicationItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drApplicationItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedPurApplication = new PurApplicationEntity();
                SelectedPurApplication.ApplicationId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedPurApplication == null)
            {
                return;
            }
            SelectedPurApplication.Status = NormalStatus.STATUS03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedPurApplication == null)
            {
                return;
            }
            SelectedPurApplication.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApplicationPerson.Text = frm.SelectedPerson.NameCn;
                txtApplicationPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtApplicationPerson.Text = "";
                txtApplicationPerson.Tag = null;
            }
        }

        private void tsmNew_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["APPLICATION_ID"] = SelectedPurApplication.ApplicationId;
            dt.Rows.Add(dr);
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drApplicationItemSelected!=null)
            {
                if (drApplicationItemSelected.RowState != DataRowState.Added)
                {
                    PurApplicationItemEntity entity = new PurApplicationItemEntity(drApplicationItemSelected);
                    DeleteList.Add(entity);
                }
                DataTable dt = gvMain.DataSource as DataTable;
                dt.Rows.Remove(drApplicationItemSelected);
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "QTY" || e.Column.FieldName == "PRICE")
            {
                decimal unitPrice = 0;
                if (string.IsNullOrEmpty(drApplicationItemSelected["PRICE"].ToString()))
                {
                    return;
                }
                else
                {
                    unitPrice += Convert.ToDecimal(drApplicationItemSelected["PRICE"].ToString());
                }
                decimal qty = 0;
                if (string.IsNullOrEmpty(drApplicationItemSelected["QTY"].ToString()))
                {
                    return;
                }
                else
                {
                    qty += Convert.ToDecimal(drApplicationItemSelected["QTY"].ToString());
                }
                DataTable dt = gvMain.DataSource as DataTable;
                dt.Rows[e.RowHandle]["TOTAL_AMOUNT"] = unitPrice * qty;
                ResetTotalAmount();
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drApplicationItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drApplicationItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drApplicationItemSelected["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                drApplicationItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drApplicationItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drApplicationItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
        }

        private void dtpDeliveryRequiredDate_ValueChanged(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                dr["DELIVERY_REQUIRED_DATE"] = dtpDeliveryRequiredDate.EditValue;
            }
        }

        private void dtpDeliveryPlanDate_ValueChanged(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                dr["DELIVERY_PLAN_DATE"] = dtpDeliveryRequiredDate.EditValue;
            }
        }

        //private void gvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (gvDetail.Columns[e.ColumnIndex].Name.Equals("colPRODUCT_CODE"))
        //    {
        //        if (gvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
        //            return;
        //        string sBlueprintCode = gvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        //        try
        //        {
        //            EsolWevServices.EsolService ws = new EsolWevServices.EsolService();
        //            byte[] arrFileData = ws.DownloadFile(sBlueprintCode + ".jpg");
        //            Image img = CommonFunctions.byteArrayToImage(arrFileData);
        //            frmProdBlueprintViewer frm = new frmProdBlueprintViewer(img);
        //            frm.ShowDialog();
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show("图片不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //    }
        //}

        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {

        }

        #endregion
    }
}
